'use strict';
const ObjectID = require('mongodb').ObjectID;
const mongo = require('mongodb');
const GridStore = require('mongodb').GridStore;
const fs = require("fs");
const path = require('path');
const Grid = require('gridfs-stream');
const Busboy = require('busboy');
const inspect = require('util').inspect;
const gm = require("gm");
module.exports = {
open:true,
  handler:(req, res, next)=>{
    const collection =   req.mongo.collection('fs.files');
    collection.findOne({_id: ObjectID(req.params.id)}, function (err, data) {
    if (err) return next(err);
    if (!data) return next("not found");
    var headers = {
      'Content-Type': data.contentType,
      'ContentDisposition': 'attachment',
      'ContentLength': data.length
      //'ContentDisposition.FileName': data.filename
    };
    //断点续传处理
    var range = req.headers.range;
    if (range) {
      var startPos, endPos;
      console.log(range);
      range = range.replace("bytes", '').replace("=", "").replace(" ", "");

      range = range.split("/")[0];
      var arr = range.split("-");
      startPos = Number(arr[0]);
      if (arr.length > 1 && arr[1].length > 0) {
        endPos = Number(arr[1])
      } else {
        endPos = data.length;
      }

      console.log(startPos);
      console.log(endPos);
      headers.content_Range = 'bytes ' + startPos + "-" + endPos + "/" + data.length;
      headers['ContentLength'] = endPos - startPos;
      if (startPos == 0 && endPos == data.length) {
        res.status(200);
      } else {
        res.status(206);
        headers['Content-Type'] = 'application/octet-stream';
      }
    }
    res.set(headers);


    var gfs = Grid(req.mongo, mongo);
    var options = {_id: ObjectID(req.params.id)};
    gfs.exist(options, function (err, found) {
      if (err) return next(err);
      if (!found)  return res.status(404).send();
      options.range = {
        startPos: startPos,
        endPos: endPos
      };
      var readstream = gfs.createReadStream(options);
      readstream.on('data', function (chunk) {
        //   console.log("readstream on data chunk size:" + chunk.length);
        res.write(chunk, 'binary');

      }).on('end', function () {
        //   console.log(data.filename + ":readstream on end");
        readstream = null;
        res.end();
      }).on('error', function (err) {
        console.log(data.filename + ":readstream on error");
        readstream = null;
        res.status(500).end();
      });
      //记录访问日志
      collection.update({_id: ObjectID(req.params.id)}, {$set: {lastOn: new Date()}, $inc: {cnt: 1}});

      req.mongo.collection('exeFile').update({_id: ObjectID(req.params.id)}, {$set: {lastOn: new Date()}, $inc: {cnt: 1}})
    })
  });

}
};
